package com.lzx.adx.report.controller.v1.wy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.common.CommonReportRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 网易-网易-创智(猫耳FM)
 */
@RequestMapping("/wy/cz")
@RestController
@Slf4j
public class WangYCZController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(CommonReportRequest requestParams, HttpServletRequest request) {
        log.info("接收到网易-创智(猫耳FM)的请求参数为{}", JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        String finalUrl = KkHeper.covertChuangZhiUrl(accountDTO, reportDTO);
        log.info("账号为{},网易-创智(猫耳FM)请求地址为{}", requestParams.getDspId(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 网易-创智(猫耳FM)上报的接口，响应的结果为{}", requestParams.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 饿了么回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("接收到创智(猫耳FM)回传到网易的请求Id:{} 类型{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("接收到创智(猫耳FM)回传到网易的请求Id空,不作处理");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long currentTimeMillis = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        } else {
            log.error("创智(猫耳FM)回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        log.info("账号为{} 请求id为{}创智(猫耳FM)回传网易转码地址为：{}", reportDTO.getDspId(), requestId, decodeUrl);
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("conv_type", "actived");
        paramsReq.put("t", currentTimeMillis);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("账号为{} 请求id为{}创智(猫耳FM)回传网易完整地址为：{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("账号为{} 请求id为{}创智(猫耳FM)回传网易转换响应的结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 是否在比例范围内
     *
     * @param per
     * @return
     */
    private static boolean shouldIdentifyAd(Double per) {
        Random random = new Random();
        double randomValue = random.nextDouble(); // 生成到1之间的随机数
        log.info("随机数为{}", randomValue);
        return randomValue > per;
    }


}
